package com.fly.uaa.config;


import com.fly.common.util.MD5Encoder;
import com.fly.uaa.security.CustomUserDetailsService;
import com.fly.uaa.security.provider.SMSAuthenticationProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * @description web权限配置
 * @author: fly
 * @date: 2018/11/26 16:34
 */
@EnableWebSecurity
@Configuration
@Order(2)
class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // CSRF:因为不再依赖于Cookie，所以你就不需要考虑对CSRF（跨站请求伪造）的防范。
        http
                .csrf().disable()
                .requestMatchers().antMatchers("/oauth/authorize", "/oauth/confirm_access", "/login")
                .and()
                .authorizeRequests()
                .antMatchers("/oauth/authorize", "/oauth/confirm_access").authenticated()
                .anyRequest().permitAll()
                //.anyRequest().permitAll()
                .and()
                .formLogin();
//                .httpBasic();
    }

    @Autowired
    public void globalUserDetails(final AuthenticationManagerBuilder auth) throws Exception {
        auth
                .inMemoryAuthentication()
                .withUser("admin")
                .password("E8zvZXDqzB1QT1pO")
                .roles("ADMIN", "ACTUATOR");
    }

    @Bean
    public AuthenticationProvider smsAuthProvider(){
        SMSAuthenticationProvider smsAuthenticationProvider = new SMSAuthenticationProvider();
        smsAuthenticationProvider.setUserDetailsService(customUserDetailsService);
        return smsAuthenticationProvider;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(customUserDetailsService)
                // 设置密码加密方式
                .passwordEncoder(new MD5Encoder());
        auth.authenticationProvider(smsAuthProvider());

    }

    @Autowired
    private CustomUserDetailsService customUserDetailsService;
}
